package com.hsr.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.hsr.web.dto.UserDTO;
import com.hsr.web.entity.TUser;
import com.hsr.web.enums.ResultCode;
import com.hsr.web.exception.ResultException;
import com.hsr.web.mapper.TUserMapper;
import com.hsr.web.service.ITUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tb
 * @since 2022-03-30
 */
@Service
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser> implements ITUserService {

    private final BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
    @Lazy
    @Autowired
    UserDetailsService userDetailsService;

    @Override
    public void updateUser(UserDTO dto) {


        TUser tUser = baseMapper.selectOne(new LambdaUpdateWrapper<>());
        if (StringUtils.hasLength(dto.getUserName())){
            tUser.setUserName(dto.getUserName());
        }
        if (StringUtils.hasLength(dto.getUserNewPwd()) && StringUtils.hasLength(dto.getUserOldPwd())){
            UserDetails userDetails = userDetailsService.loadUserByUsername("admin");
            boolean matches = encoder.matches(dto.getUserOldPwd(), userDetails.getPassword());
            if (!matches){
                throw new ResultException(ResultCode.USER_PASSWORD_WRONG);
            }
            tUser.setUserPwd(encoder.encode(dto.getUserNewPwd()));
        }
        baseMapper.updateById(tUser);
    }
}
